package com.jh.readme.iu.activity.pdetail;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.jh.readme.R;
import com.jh.readme.iu.activity.pdetail.adpter.OnPageChangeListenerAdapter;
import com.jh.readme.iu.activity.pdetail.adpter.PhotoAdapter;
import com.jh.readme.widgets.HackyViewPager;
import com.jh.readme.widgets.ThreePointLoadingView;
import com.jh.readme.widgets.util.MeasureUtil;
import com.jh.tools.base.BaseActivity;
import com.jh.tools.bean.SinaPhotoDetailPicsEntity;
import com.jh.tools.common.StringUtils;

import java.util.List;

import zhou.widget.RichText;

/**
 * 图片详情页
 */
public class PictureDetailActivity extends BaseActivity<PictureDetailPresenter,PictureDetailModel>implements PictureDetailContract.View, View.OnClickListener{

    private ThreePointLoadingView mLoadingView;
    // 捕获安卓系统报的一个bug
    private HackyViewPager mViewPager;
    private TextView mTitleTv;
    private TextView mPageTv;
    private RichText mContentTv;
    private int mTitleTvPaddingTop;
    private int mContentTvPaddingBottom;
    private int mOffset;
    private ValueAnimator mAnimator;
    private int mContentTvWidth;
    private int mPageTvWidth;
    @Override
    public int getLayoutId() {
        return R.layout.activity_picture_detail;
    }

    @Override
    public void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mLoadingView = (ThreePointLoadingView) findViewById(R.id.tpl_view);
        mLoadingView.setOnClickListener(this);

        mViewPager = (HackyViewPager) findViewById(R.id.viewpager);

        mTitleTv = (TextView) findViewById(R.id.tv_photo_detail_title);

        mPageTv = (TextView) findViewById(R.id.tv_photo_detail_page);

        mContentTv = (RichText) findViewById(R.id.tv_photo_detail_content);

        String photoId = getIntent().getStringExtra("photoId");



    }

    @Override
    public void initPresenter() {
      mPresenter.setVM(this,mModel,this);
    }
    /**
     * 根据文本的长度动态设置对齐方式
     */
    private void dynamicSetTextViewGravity() {
        if ((mContentTv.getPaint()
                .measureText(mContentTv.getText().toString()) < mContentTvWidth)) {
            mContentTv.setGravity(Gravity.CENTER);
            // 设为中心对齐，去掉前面两个空格
            mContentTv.setRichText(StringUtils.replaceBlank(mContentTv.getText().toString()));
            LogUtils.e("设为中心对齐，去掉前面两个空格");
        } else {
            mContentTv.setGravity(Gravity.TOP | Gravity.START);
            LogUtils.e("设为原始对齐");
        }
    }

    /**
     * 图片被拉大时控制页面其他元素隐藏
     *
     * @param show
     */
    private void controlView(boolean show) {
        if (mAnimator != null && mAnimator.isRunning()) {
            return;
        }
        mAnimator = new ValueAnimator();
        if (!show && (boolean) mTitleTv.getTag()) {
            // 隐藏
            mAnimator.setIntValues(0, mOffset);
            mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {

                    mTitleTv.setTag(false);
                    mTitleTv.setPadding(mTitleTv.getPaddingLeft(),
                            -(int) animation.getAnimatedValue(), mTitleTv.getPaddingRight(),
                            mTitleTv.getPaddingBottom());

                    mContentTv.setPadding(mContentTv.getPaddingLeft(), mContentTv.getPaddingTop(),
                            mContentTv.getPaddingRight(), -(int) animation.getAnimatedValue());

                    ViewCompat.setScaleX(mPageTv, 1 - animation.getAnimatedFraction());
                    ViewCompat.setScaleY(mPageTv, 1 - animation.getAnimatedFraction());

                }
            });
        } else if (show && !(boolean) mTitleTv.getTag()) {
            // 显示
            mAnimator = new ValueAnimator();
            mAnimator.setIntValues(mOffset, 0);
            mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {

                    mTitleTv.setTag(true);
                    mTitleTv.setPadding(mTitleTv.getPaddingLeft(),
                            -(int) animation.getAnimatedValue() + mTitleTvPaddingTop,
                            mTitleTv.getPaddingRight(), mTitleTv.getPaddingBottom());

                    mContentTv.setPadding(mContentTv.getPaddingLeft(), mContentTv.getPaddingTop(),
                            mContentTv.getPaddingRight(),
                            -(int) animation.getAnimatedValue() + mContentTvPaddingBottom);

                    ViewCompat.setScaleX(mPageTv, animation.getAnimatedFraction());
                    ViewCompat.setScaleY(mPageTv, animation.getAnimatedFraction());
                }
            });
        } else {
            return;
        }
        mAnimator.setDuration(300);
        mAnimator.start();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && mTitleTvPaddingTop == 0) {
            mTitleTvPaddingTop = mTitleTv.getPaddingTop();
            mContentTvPaddingBottom = mContentTv.getPaddingBottom();
        }
    }
    public void initViewPager(final List<SinaPhotoDetailPicsEntity> photoList) {

        mOffset = MeasureUtil.getScreenSize(this).y / 4;

//        mTitleTv.setText(photoList.data.title);
        mTitleTv.setTag(true);

        final PhotoAdapter photoAdapter = new PhotoAdapter(this, photoList);
        mViewPager.setAdapter(photoAdapter);

        final OnPageChangeListenerAdapter mPageChangeListenerAdapter = new OnPageChangeListenerAdapter() {

            @Override
            public void onPageSelected(int position) {
                final String s = getString(R.string.photo_page, position + 1,
                        photoList.size());

                mPageTv.setText(s);

//                final String alt = photoList.get(position).alt;
//                if (!TextUtils.isEmpty(alt) && !alt
//                        .equals(mContentTv.getText().toString().trim())) {
//                    ObjectAnimator.ofFloat(mContentTv, "alpha", 0.5f, 1).setDuration(500).start();
//                    mContentTv.setRichText(getString(R.string.photo_detail_content, alt));
//                    dynamicSetTextViewGravity();
//                }

                // 每次切换回来都要处理一下，因为切换回来当前的图片不会调用OnPhotoExpandListener的onExpand方法
                controlView(photoAdapter.getPics().get(position).isShowTitle());

            }

        };

        mViewPager.addOnPageChangeListener(mPageChangeListenerAdapter);

        mContentTv.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        mPageTvWidth = mPageTv.getMeasuredWidth();
                        mContentTvWidth = mContentTv.getMeasuredWidth();
                        LogUtils.e("长度：" + mPageTvWidth + ";" + mContentTvWidth);
                        mPageChangeListenerAdapter.onPageSelected(0);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            mContentTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }
                });

        photoAdapter.setOnPhotoExpandListener(new PhotoAdapter.OnPhotoExpandListener() {
            @Override
            public void onExpand(boolean show, int position) {
                // KLog.e("回调的时候: " + show);
                if (mViewPager.getCurrentItem() == position) {
                    // 当前页码才处理
                    controlView(show);
                }
            }
        });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.removeAllUpdateListeners();
            mAnimator.cancel();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tpl_view:
                break;
        }
    }
}
